/*
Copyright (c) 2007,2007 Elizeu Nogueira da R. Jr.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the Elizeu Nogueira da R. Jr. nor the names of its 
      contributors may be used to endorse or promote products derived from this 
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


This package is based on HypersonicSQL, originally developed by Thomas Mueller.
and HSQLDB original developed by the HSQL Development Group
*/

package br.com.dreamsource.mobile.jmesql;

import br.com.dreamsource.mobile.jmesql.exceptions.SQLException;
import br.com.dreamsource.mobile.jmesql.sql.Types;
import java.io.*;
import java.util.*;
import br.com.dreamsource.mobile.jmesql.jdbcStatement;

public class jdbcPreparedStatement extends jdbcStatement {
    private String sSql;
    private Vector vParameter;
    
    public jdbcResultSet executeQuery() throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return super.executeQuery(build());
    }

    public int executeUpdate() throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return super.executeUpdate(build());
    }

    public void setNull(int parameterIndex, int sqlType) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	setNull(parameterIndex);
    }

    public void setBoolean(int parameterIndex,
			   boolean x) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	setParameter(parameterIndex, x ? "TRUE" : "FALSE");
    }
    
    public void setDouble(int parameterIndex, double x) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	setParameter(parameterIndex, "" + x);
    }

    public void setInt(int parameterIndex, int x) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	setParameter(parameterIndex, "" + x);
    }

    public void setFloat(int parameterIndex, float x) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	setParameter(parameterIndex, "" + x);
    }

    public void setString(int parameterIndex, String x) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	if (x == null) {
	    setNull(parameterIndex);
	} else {
	    setParameter(parameterIndex, Column.createString(x));
	}
    }

    public void setDate(int parameterIndex,
			java.util.Date x) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	if (x == null) {
	    setNull(parameterIndex);
	} else {
	    setParameter(parameterIndex, "'" + x.toString() + "'");
	}
    }

    public void clearParameters() {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	vParameter.removeAllElements();
    }

    public boolean execute() throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return super.execute(build());
    }

    private void setParameter(int i, String s) {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	if (vParameter.size() < i) {
	    vParameter.setSize(i);
	}

	vParameter.setElementAt(s, --i);
    }

    private String getParameter(int i) {
	if (i >= vParameter.size()) {
	    return null;
	}

	return (String) vParameter.elementAt(i);
    }

    private String build() {
	if (vParameter.isEmpty()) {
	    return sSql;
	}

	StringBuffer s = new StringBuffer();
	int	     i = 0, l = sSql.length();
	boolean      bSkip = false, bSkip2 = false;

	for (int j = 0; j < l; j++) {
	    char c = sSql.charAt(j);

	    if (c == '?' &&!bSkip &&!bSkip2) {
		s.append(getParameter(i++));
	    } else {
		if (c == '\'' &&!bSkip2) {
		    bSkip = !bSkip;
		} else if (c == '"' &&!bSkip) {
		    bSkip2 = !bSkip2;
		}

		s.append(c);
	    }
	}

	return s.toString();
    }

    private void setNull(int parameterIndex) {
	setParameter(parameterIndex, "NULL");
    }

    public void registerOutParameter(int parameterIndex,
				     int sqlType) throws SQLException {
	throw getNotSupported();
    }

    public void registerOutParameter(int parameterIndex, int sqlType,
				     int scale) throws SQLException {
	throw getNotSupported();
    }

    public boolean wasNull() throws SQLException {
	throw getNotSupported();
    }

    public String getString(int parameterIndex) throws SQLException {
	throw getNotSupported();
    }

    public boolean getBoolean(int parameterIndex) throws SQLException {
	throw getNotSupported();
    }

    public int getInt(int parameterIndex) throws SQLException {
	throw getNotSupported();
    }

    public  float getFloat(int parameterIndex) throws SQLException {
	throw getNotSupported();
    }

    public java.util.Date getDate(int parameterIndex) throws SQLException {
	throw getNotSupported();
    }

    public java.util.Date getDate(int parameterIndex,
				 Calendar cal) throws SQLException {
	throw getNotSupported();
    }

    public void registerOutParameter(int paramIndex, int sqlType,
				     String typeName) throws SQLException {
	throw getNotSupported();
    }

    public void addBatch() throws SQLException {
	throw getNotSupported();
    }

    public void setDate(int parameterIndex, java.util.Date x,
			Calendar cal) throws SQLException {
        
	setDate(parameterIndex, x);
    }

    public void setNull(int parameterIndex, int sqlType,
			String typeName) throws SQLException {
	setNull(parameterIndex, sqlType);
    }

    jdbcPreparedStatement(jdbcConnection c, String s) {
	super(c);

	sSql = s;
	vParameter = new Vector();
    }

    private void setObjectInType(int parameterIndex, Object x,
				 int type) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	if (x == null) {
	    setNull(parameterIndex);

	    return;
	}

	switch (type) {
            case Types.INTEGER:
                setInt(parameterIndex, ((Integer) x).intValue());
                break;
            case Types.FLOAT:
                setDouble(parameterIndex, ((Double) x).doubleValue());
                break;
            case Types.CHAR:
            case Types.VARCHAR:
                setString(parameterIndex, (String) x);
                break;
            case Types.DATE:
                setDate(parameterIndex, (java.util.Date) x);
                break;
            default:
                setParameter(parameterIndex, x.toString());
                break;
	}
    }

    private SQLException getNotSupported() {
	return Trace.error(Trace.FUNCTION_NOT_SUPPORTED);
    }

}
